`
https://leetcode.cn/problems/capacity-to-ship-packages-within-d-days/
`

/**
 * @param {number[]} weights
 * @param {number} days
 * @return {number}
 */
var shipWithinDays = function (weights, days) {
  // 右边界初始化为可能出现的最大值
  let left = 0, right = 0

  for (let w of weights) {
    left = Math.max(left, w);
    right += w;
  }

  // 用 x 包裹/天的速度搬运，需要 f(x) 天才能搬完
  const f = (x) => {
    let needDay = 0;
    for (let i = 0; i < weights.length;) {
      // 尽可能多装货物
      let cap = x;
      while (i < weights.length) {
        if (cap < weights[i])
          break;
        else
          cap -= weights[i];
        i++;
      }
      needDay++;
    }
    return needDay;
  }

  while (left <= right) {
    const mid = left + Math.floor((right - left) / 2)
    const cur = f(mid)

    if (cur > days) {
      left = mid + 1
    } else {
      right = mid - 1
    }
    // if (cur > days) {
    //   left = mid + 1
    // } else if (cur < days) {
    //   right = mid - 1
    // } else if (cur === days) {
    //   right = mid - 1
    // }
  }

  return left
};